<div class="layui-card layadmin-header">
  <div class="layui-breadcrumb" lay-filter="breadcrumb">
    <a lay-href="">主页</a>
    <a><cite>资金归集</cite></a>
    <a><cite>营销红包分账</cite></a>
    <a><cite>红包记录</cite></a>
  </div>
</div>

<div class="layui-fluid">
  <div class="layui-card">
    <div class="layui-tab layui-tab-brief">
      <ul class="layui-tab-title">
        <li class="layui-this">红包明细</li>
      </ul>
      <div class="layui-tab-content">
        <div class="layui-tab-item layui-show">
          <div class="layui-row">
            <div class="layui-form" style="float:right;">
              <div class="layui-form-item" style="margin:0;">
                <div class="layui-input-inline">
                  <input type="text" name="searchAccountTemplateId" id="searchAccountTemplateId" placeholder="账户模板ID" autocomplete="off" class="layui-input">
                </div>
                <div class="layui-input-inline">
                </div>
                <div class="layui-input-inline">
                  <select name="type" id="searchTaskStatus" placeholder="任务状态" lay-search="">
                    <option value="">任务状态</option>
                    <option value=0>创建失败</option>
                    <option value=1>创建成功</option>
                    <option value=2>发放中</option>
                    <option value=3>发放完成</option>
                  </select>
                </div>
                <a id="search" class="layui-btn" data-type="reload"><i class="layui-icon layui-icon-search"></i>搜索</a>
              </div>
            </div>
          </div>
          <div class="layui-form-item" style="margin-top: 10px">
            <blockquote class="layui-elem-quote" id="amountTip">
              今日发放总额:<span id="todayGrantAmount" style="color: blue; margin-right: 10px;"></span>
              昨日发放总额:<sapn id="yesterDayGrantAmount" style="color: blue; margin-right: 10px;"></sapn>
            </blockquote>
          </div>
          <div class="layui-row">
            <div class="layuiAdmin-btns" style="margin-bottom: 10px;"></div>
          </div>
          <table id="XxPay_Mgr_Alipay_Cash_dataAll" lay-filter="XxPay_Mgr_Alipay_Cash_dataAll"></table>
        </div>

      </div>
    </div>
  </div>
</div>

<script>
  layui.use(['admin', 'table', 'util'], function(){
    var $ = layui.$
      ,admin = layui.admin
      ,table = layui.table
      ,element = layui.element
      ,view = layui.view
      ,form = layui.form;

    element.render('breadcrumb', 'breadcrumb');

    $.setGrantResult = function() {

        var accountTemplateId = $('#searchAccountTemplateId').val();
        var taskStatus = $('#searchTaskStatus').val();

        admin.req({
            type: 'get',
            url: layui.setter.baseUrl + '/alipayCash/statistic',
            data: {"ps[accountTemplateId]": accountTemplateId, "ps[taskStatus]": taskStatus},
            error: function(err){
                layer.alert(JSON.stringify(err.field), {
                    title: '错误提示'
                })
            },
            success: function(res){
                if(res.code == 0){
                    $('#yesterDayGrantAmount').html("￥" + res.data.yesterdayAmount/100.00);
                    $('#todayGrantAmount').html("￥" + res.data.todayAmount/100.00);
                }
            }
        });
    };

    var tplTaskStatus = function(d){
      if(d.taskStatus == 0) {
        return "<span style='color: red'>创建失败</span>";
      }else if (d.taskStatus == 1){
        return "<span style='color: blue'>创建成功</span>";
      }else if (d.taskStatus == 2){
          return "<span style='color: orangered'>发放中</span>";
      }else if (d.taskStatus == 3){
          return "<span style='color: green'>发放完成</span>";
      } else if (d.taskStatus == 4){
          return "<span style='color: red'>已取消发放</span>";
      }
    };

    var prizeType = function(d){
      if(d.prizeType == 'random') {
        return "<span style='color: blue'>随机金额</span>";
      }else if (d.prizeType == 'fixed'){
        return "<span style='color: green'>固定金额</span>";
      }
    };

    var tplAlipayStatus = function(d){
      if(d.alipayStatus == 'CREATED') {
        return "<span style='color: red'>未打款</span>";
      }else if (d.alipayStatus == 'PAID'){
        return "<span style='color: blue'>已打款</span>";
      }else if (d.alipayStatus == 'READY'){
          return "<span style='color: orangered'>已开始</span>";
      }else if (d.alipayStatus == 'PAUSE'){
          return "<span style='color: orangered'>已暂停</span>";
      }else if (d.alipayStatus == 'CLOSED'){
          return "<span style='color: red'>已结束</span>";
      }else if (d.alipayStatus == 'SETTLE'){
          return "<span style='color: green'>已清算</span>";
      }else{
          return "";
      }
    };


      // 任务状态：0-创建失败, 1-创建成功, 2-红包发放中, 3-红包发放完成 4-已取消发放
      // 支付宝红包状态：CREATED: 已创建未打款, PAID:已打款, READY:活动已开始, PAUSE:活动已暂停, CLOSED:活动已结束, SETTLE:活动已清算
    var tplOp = function(d){

        var viewHtml = '<a class="layui-btn layui-btn-normal layui-btn-xs" lay-event="view"><i class="layui-icon layui-icon-about"></i>详情</a>';
        var thisAlipayPayUrl = d.alipayPayUrl;
        if(thisAlipayPayUrl && thisAlipayPayUrl.indexOf("goto\=")){
            thisAlipayPayUrl = thisAlipayPayUrl.substring(thisAlipayPayUrl.indexOf("goto\=") + 5);
        }
        var payHtml = '<a class="layui-btn layui-btn-danger layui-btn-xs"  target="_blank" href="'+thisAlipayPayUrl+'" lay-event="pay"><i class="layui-icon layui-icon-rmb"></i>支付</a>';
        var selectNewHtml = '<a class="layui-btn layui-btn-xs" lay-event="selectNew"><i class="layui-icon layui-icon-search"></i>查询并更新最新状态</a>  &nbsp;|';
        var triggerHtml = '<a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="trigger"><i class="layui-icon layui-icon-release"></i>发红包</a>';
        var cancelCashHtml = '<a class="layui-btn layui-btn-warm layui-btn-xs" lay-event="cancelCash"><i class="layui-icon layui-icon-close"></i>取消发放</a>';

        if(d.taskStatus == 0 ){ //创建失败 只有查看按钮
            return viewHtml;
        }

        if(d.taskStatus == 2){ //红包发放中 [查看] [取消发放]
            return viewHtml + cancelCashHtml;
        }

        if(d.taskStatus == 3 ){ //红包发放完成 ： [查看] [查询并更新最新状态]
            return selectNewHtml + viewHtml ;
        }

        if(d.taskStatus == 4 ){ //已取消发放 ： [查看] [查询并更新最新状态]
            return selectNewHtml + viewHtml ;
        }

        //以下为：创建成功状态

        if(d.alipayStatus == 'CREATED'){ //已创建未打款： [查看] [查询并更新最新状态] [支付] [取消发放]
            return selectNewHtml + viewHtml + payHtml + cancelCashHtml;
        }

        if(d.alipayStatus == 'PAID' || d.alipayStatus == 'READY'){ //已打款 | 开始 ： [查看] [查询并更新最新状态] [发红包] [取消发放]
            return selectNewHtml + viewHtml +  triggerHtml + cancelCashHtml;
        }

        if(d.alipayStatus == 'PAUSE'){ //已暂停 ： [查看] [查询并更新最新状态] [取消发放]
            return  selectNewHtml + viewHtml + cancelCashHtml;
        }

        //活动结束， 活动已清算
        return viewHtml;
    }


    //商户列表
    table.render({
      elem: '#XxPay_Mgr_Alipay_Cash_dataAll'
      ,url: layui.setter.baseUrl + '/alipayCash/list' //列表接口
      ,where: {
          access_token: layui.data(layui.setter.tableName).access_token
      }
      ,id: 'tableReload'
      ,page: true
      ,cols: [[
        {field: 'accountTemplateId', title: '账号模板ID'}
        ,{title: '发放方式', templet: prizeType}
        ,{title: '发放总金额(元)', templet: '<div>{{ d.totalMoney/100 }}</div>'}
        ,{title: '已发放金额(元)', templet: '<div>{{ d.alipaySendAmount/100 }}</div>'}
        ,{field: 'totalNum', title: '发放个数'}
        ,{title: '任务状态', templet: tplTaskStatus}
        ,{title: '支付宝红包状态', templet: tplAlipayStatus}
        ,{title: '创建时间', width:180, templet: '<div>{{ layui.util.toDateString(d.createTime, "yyyy-MM-dd HH:mm:ss") }}</div>'}
        ,{field: 'edit', title: '操作', fixed: "right", width: 400, templet: tplOp }
      ]]
      ,skin: 'line'
      ,done: function () {
          $.setGrantResult();
      }
    });


    var thisLayerId  = null; //当前弹层ID
    var thisCashId  = null; //当前处理的红包ID

    //点击【支付】弹层显示内容
    var toPayHtml = `
              <div class="layui-form-item" style="margin-top:20px; margin-bottom: 30px">

                  <div class="layui-form-item" style="margin-left:170px; margin-bottom: 20px;">
                      <label>请确认是否支付完成？</label>
                  </div>

                  <div class="layui-input-block">
                      <button type="button" class="layui-btn layui-btn-normal redCashPayFinishOrFail">
                          <i class="layui-icon layui-icon-ok-circle"></i>支付完成
                       </button>
                      <button type="button" class="layui-btn layui-btn-danger redCashPayFinishOrFail">
                          <i class="layui-icon layui-icon-about"></i>支付遇到问题
                      </button>
                  </div>
              </div>
      `;

    var selectNewFunc = function(cashId){
        //正在查询状态。。。
        var layerMsgId = layer.msg('正在查询红包最新状态...',{time: 0, shade: 0.3});
        admin.req({
            type: 'get',
            url: layui.setter.baseUrl + '/alipayCash/updateAlipayStatus',
            data: {cashId: cashId},
            error: function (err) {layer.close(layerMsgId);layer.alert(err);},
            success: function (res) {
                layer.close(layerMsgId);
                if(res.data){
                    layer.msg('查询成功！');
                    table.reload('tableReload');
                }else{
                    layer.msg('查询失败！');
                }
            }
        });
    }

    //监听工具条
    table.on('tool(XxPay_Mgr_Alipay_Cash_dataAll)', function(obj){
      var data = obj.data;
      if(obj.event === 'view'){
          view.xxpayPopup("红包记录详情", "cash_coll/alipay_cash/list/view", {id: data.id}, {btn:false});
      }else if(obj.event === 'selectNew'){ //查询并更新最新状态
          selectNewFunc(data.id);
        }else if(obj.event === 'pay'){
          thisCashId = data.id;
          thisLayerId = layer.open({ type: 1, closeBtn:false, area: ['500px', 'auto'], title: '等待支付', content: toPayHtml });
        }else if(obj.event === 'cancelCash'){

          //取消发放  -》 查询红包最新状态， 如果当前状态为【未打款】, 将任务状态改为： 已取消发放。
          layer.confirm("确认取消红包发放？ <br/> 如已支付，退款进度以支付宝为准！<br/>  如正在发放中，已发放部分无法退回，未领取金额退款进度以支付宝为准！", function(){

              //请等待，正在创建【发红包】任务
              var layerMsgId = layer.msg('请等待，正在取消任务... ',{time: 0, shade: 0.3});
              admin.req({
                  type: 'get',
                  url: layui.setter.baseUrl + '/alipayCash/cancelAlipayCash',
                  data: {cashId: data.id},
                  error: function (err) {
                      layer.close(layerMsgId);
                      layer.alert(err);
                  },
                  success: function (res) {
                      layer.close(layerMsgId);
                      if(res.code == '0'){ //成功取消任务
                          layer.msg('任务取消成功');
                          table.reload('tableReload');
                      }else{ //任务取消失败
                          layer.alert(res.errMsg);
                      }
                  }
              });
          });
      }

        else if(obj.event === 'trigger'){

          layer.confirm("确认发送红包到分账用户？", function(){

              //请等待，正在创建【发红包】任务
              var layerMsgId = layer.msg('请等待，正在创建[发红包]任务... ',{time: 0, shade: 0.3});
              admin.req({
                  type: 'get',
                  url: layui.setter.baseUrl + '/alipayCash/tiggerAlipayCash',
                  data: {cashId: data.id},
                  error: function (err) {
                      layer.close(layerMsgId);
                      layer.alert(err);
                  },
                  success: function (res) {

                      layer.close(layerMsgId);
                      if(res.code == '0'){ //成功创建任务
                          layer.msg('任务创建完成');
                          table.reload('tableReload');
                      }else{ //任务创建失败
                          layer.alert(res.errMsg);
                      }
                  }
              });
          });
        }

    });

    // 搜索
    var $ = layui.$, active = {
      reload: function(){
        var accountTemplateId = $('#searchAccountTemplateId').val();
        var taskStatus = $('#searchTaskStatus').val();
        //执行重载
        table.reload('tableReload', {
          page: {
            curr: 1 //重新从第 1 页开始
          }
          ,where: {
                accountTemplateId: accountTemplateId,
                taskStatus: taskStatus
          }
        });
      }
    };
    $('#search').on('click', function() {
      var type = $(this).data('type');
      active[type] ? active[type].call(this) : '';
    });


    $("body").off('click', '.redCashPayFinishOrFail');
    $("body").on('click', '.redCashPayFinishOrFail', function() { //点击【支付完成/支付遇到问题】按钮点击事件
        layer.close(thisLayerId);
        selectNewFunc(thisCashId);
    });



    // 渲染表单
    form.render();
  });
</script>